<template>
  <div class="qr">
    <canvas ref="qrcodeCanvas"></canvas>
  </div>
</template>

<script>
import QRCode from "qrcode";
export default {
  name: "QRCode",
  components: {},
  props: {
    url: {
      type: String,
      required: true,
    },
    size: {
      type: Number,
      default: 360,
    },
  },
  data() {
    return {
      logo: require("@/assets/icon/common/logo.png"),
      logoScale: 0.15,
    };
  },
  watch: {},
  computed: {},
  methods: {
    async generateQRCode() {
      try {
        const canvas = this.$refs.qrcodeCanvas;
        const ctx = canvas.getContext("2d");
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        await QRCode.toCanvas(canvas, this.url, {
          width: this.size,
          margin: 2,
          errorCorrectionLevel: "H",
        });
        const logo = new Image();
        logo.src = this.logo;
        logo.onload = () => {
          const logoSize = canvas.width / 4;
          const x = (canvas.width - logoSize) / 2;
          const y = (canvas.height - logoSize) / 2;

          // 绘制白色背景
          ctx.fillStyle = "#ffffff";
          ctx.fillRect(x - 5, y - 5, logoSize + 10, logoSize + 10);

          // 绘制Logo
          ctx.drawImage(logo, x, y, logoSize, logoSize);
        };
      } catch (error) {
        console.error("生成失败:", error);
      }
    },
  },
  created() {},
  mounted() {
    this.generateQRCode();
  },
  beforeDestroy() {},
};
</script>
<style lang="less" scoped>
.qr {
  padding: 10px;
  width: 440px;
  box-sizing: border-box;
  background: #fff;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  canvas {
    max-width: 100%;
    height: auto !important;
    user-select: none;
  }
}
</style>